package com.szrt.zw.test.base;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.szrt.zw.test.student.entity.StudentEntity;



public abstract class BaseController<T> {
	
	public abstract BaseService<T> getBaseService();
	
	
	@ResponseBody
	@RequestMapping("/add")
	public Map<String,String> add(T entity){
		Map<String,String> map  = new HashMap<String,String>();
		int counter = getBaseService().add(entity);
		if(counter ==1){
			map.put("msg", "增加成功...");
			map.put("result", "success");
		}else{
			map.put("msg", "增加失败...");
			map.put("result", "failure");
		}
		return map;
	}
	
	@ResponseBody
	@RequestMapping("/deleteByIds")
	public Map<String,String> deleteByIds(String id){
		Map<String,String> map  = new HashMap<String,String>();
		String []idss=id.split(",");
		 List<Integer> listids=new ArrayList<Integer>();
		 for (int i = 0; i < idss.length; i++) {
			listids.add(Integer.parseInt(idss[i]));
		}
		int counter = getBaseService().deleteByIds(listids);
		if(counter > 0){
			map.put("msg", "删除成功...");
			map.put("result", "success");
		}else{
			map.put("msg", "删除失败...");
			map.put("result", "failure");
		}
		return map;
	}
	@ResponseBody
	@RequestMapping("/update")
	public Map<String,String> update(T entity){
		
		Map<String,String> map  = new HashMap<String,String>();
		int counter =  getBaseService().update(entity);
		if(counter ==1){
			map.put("msg", "修改成功...");
			map.put("result", "success");
		}else{
			map.put("msg", "修改失败...");
			map.put("result", "failure");
		}
		
		return map;
	}
	
	@ResponseBody
	@RequestMapping("/findById")
	public T findById(Integer id){
		return getBaseService().findById(id);
	}
	@ResponseBody
	@RequestMapping("/findAll")
	public Map<String,Object> findAll(Integer page, Integer rows,String studentName,String className){
		Integer before = (page -1)*rows;
		Integer after = rows;
		Map<String,Object> pageMap = new HashMap<String,Object>();
		pageMap.put("before", before);
		pageMap.put("after", after);
		 try {
			 if (null!=studentName && !"".equals(studentName.trim())) {
				 pageMap.put("studentName", studentName+"%");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		 try {
			 if (null!=className && !"".equals(className.trim())) {
				 pageMap.put("className", className+"%");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<StudentEntity> list= getBaseService().findAll(pageMap);
		
		Map<String,Object> map=new HashMap<>();
		int  total = getBaseService().getTotalCounter(pageMap);
		map.put("total", total);
		map.put("rows",list);
		map.put("result","success");
		return map;
	}


}
